package top.codedance.iotp.server.net.handle.otherHandle;

import cd.io.netty.channel.ChannelHandlerContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.common.entity.CommonEntity;
import top.codedance.iotp.server.ServerApplication;
import org.apache.log4j.Logger;

import java.nio.charset.StandardCharsets;

public class ReportLoadHandle implements Runnable {
    private static Logger logger = ServerApplication.getLogger(ReportLoadHandle.class);
    private ChannelHandlerContext channelHandlerContext;
    private CommonEntity commonEntity;

    public ReportLoadHandle(ChannelHandlerContext channelHandlerContext, CommonEntity commonEntity) {
        this.channelHandlerContext = channelHandlerContext;
        this.commonEntity = commonEntity;
    }

    @Override
    public void run() {
        byte[] body = commonEntity.getBody();
        String jsonStr = new String(body, StandardCharsets.UTF_8);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String deviceId = jsonObject.getString("deviceId");
        String load = jsonObject.getJSONObject("load").toJSONString();
        String os = jsonObject.getString("os");
        ServerApplication.clientsLoadInfo.put(deviceId, load);
        ServerApplication.clientsOsInfo.put(deviceId, os);
//        receive();
        logger.debug("Get client[" + deviceId + "] load infomation: " + load);
    }

    public void receive() {
        try {
            CommonEntity commonEntity2 = new CommonEntity();
            commonEntity2.setCommand(Command.REPORT_LOAD_RECEIVE);
            commonEntity2.setBody("Success".getBytes(StandardCharsets.UTF_8));
            channelHandlerContext.writeAndFlush(commonEntity2.build());
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
    }
}
